/*
* 任务量导入
* 
*/
public with sharing class AssignmentsImportController {


	public String backId {get;private set;}
	public Boolean isErr {get;private set;}

	public Boolean isSuc {get;private set;}
	public String msg {get;private set;}
	public TaskTrackingImport__c approvalT {get;private set;}
	public String dataJson {get;private set;}
	public String saveJson {get; set;}
    public String catesJson  {get;private set;}


	 public AssignmentsImportController(ApexPages.StandardController con ) {

    	backId = System.currentPageReference().getParameters().get('id');
    	approvalT = new TaskTrackingImport__c();
    	setNil();
    }
    public AssignmentsImportController() {

    	backId = System.currentPageReference().getParameters().get('id');
    	approvalT = new TaskTrackingImport__c();
    	setNil();
    }


    private Map<String,Set<String>> getCates (){
        Map<String,Set<String>> pMp = new Map<String,Set<String>>();
        for(ProductStructure__c p : [select  Classify1__c ,Classify2__c  from ProductStructure__c where Classify2__c != null ]){

            boolean f = pMp.containsKey(p.Classify1__c);
            Set<String> cls = f ? pMp.get(p.Classify1__c) : new Set<String>();
            cls.add(p.Classify2__c);
            if(!f) pMp.put(p.Classify1__c,cls);
        }
        pMp.put('无', new Set<String>{'无'});
        return pMp;
    } 
      
    public void init(){

    	try {

    		User u = [select Id ,Profile.Name from User  where Id = :UserInfo.getUserId()];
            catesJson = EncodingUtil.urlEncode(JSON.serialize(getCates()), 'UTF-8');
            
    		//新建
    		if(String.isBlank(backId)){
    			 approvalT.RecordTypeId = Utils.getRecordTypeIdByDevNameAndObjName('ApprovalForm', 'TaskTrackingImport__c');	
    			 approvalT.Status__c = '草案中';


    		}else{
    			//编辑
    			approvalT = [select Id,Status__c  from TaskTrackingImport__c where Id=:backId  ];

    		}

    		if((approvalT.Status__c == '已批准' || approvalT.Status__c == '审批中'	) && u.Profile.Name != '系统管理员' && u.Profile.Name != '财务部总监') throw new DmlException(approvalT.Status__c  +' 不能操作!');


    	    
    	}catch (Exception e) {
    		isErr = true;
    	    ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));

    	}


    	
    }
    public void setNil(){
    	dataJson = '[]';
    	saveJson = '[]';
    }
    //获取明细
    public void getDetails(){

    	if(backId == null)return;
    	List<Map<String,String>> datas = new List<Map<String,String>>();
    	Map<String,String>  comMap  = getCompanyMap(true);// ImportObject.getPicklistValues('TaskTrackingImport__c','Company__c', true );
        Map<String,String> shortcomMap = getCompanyMap(false);

    	Set<String> iemiset = new Set<String>();
    	Set<String> accset = new Set<String>();
    	//SubRito__c,
        for(TaskTrackingImport__c tt :[select Id ,Instrumentstartdate__c  , Enddateofinstrument__c,TaskSource__c,
            OwnerCompany__c,OwnerYM__c,Company__c,MCode__c,Outgoingway__c,EnterWay__c,
            OutgoingNumber__c,InstrumentType__c,SerialNo__c,Numberofyears__c,ContractYear__c,
            ContractStartDate__c,ContractEndDate__c,ContractNumber__c,OverallPackagingMode__c,Contract__c,
            CalculationTable__c,MKCooperationType__c,OutdoorDate__c,EstimateNumber__c,
            InstrumentName__r.Category1__c,

            EquipTaxPrice__c, Account__c , 

            Account__r.Name , TerminalCustomer__r.Name ,InstrumentDeliveryCost__c,SubcompanyInstrumentDeliveryCost__c,
            InstrumentName__r.ProductName__c  ,IsSplited__c ,InstrumentName__r.NCCode__c,Tax__c,EquipNote__c,TaskDetailNote__c,
            (select Classification1__c, Classification2__c,ReagentBrand__c,GroupGrossProfit__c,SubCompanyGrossProfit__c,
             Years__c,WhetherNew__c,WhetherCovered__c,ReagentAssignments__c
             from TaskTrackingImport__r )
            from TaskTrackingImport__c where MainApply__c =:backId and IsSplited__c != true   order by Mcode__c  ]){
        	//and IsSplited__c != true

            Map<String,String> d = new Map<String,String>();
            d.put('sfid', tt.Id);
            d.put('owner_year_month',tt.OwnerYM__c  );
            d.put('owner_area', tt.OwnerCompany__c);
            d.put('sign_company',comMap.get(tt.Company__c ));

            d.put('sf_pay_account_id', tt.Account__r.Name );

            d.put('sf_ter_account_id',tt.TerminalCustomer__r.Name  );
            
            accset.add(shortcomMap.get(tt.OwnerCompany__c));
            iemiset.add(tt.SerialNo__c);

            d.put('invname', tt.InstrumentName__r.ProductName__c);
            d.put('invcate', tt.InstrumentName__r.Category1__c);


            d.put('iemi', tt.SerialNo__c );         
            d.put('coop_start_date', tt.Instrumentstartdate__c.format());
            d.put('coop_end_date',tt.Enddateofinstrument__c.format() );

           // d.put('sub_rito',String.valueOf(tt.SubRito__c) );
            d.put('tax_price',String.valueOf(tt.EquipTaxPrice__c) );

            d.put('nccode', tt.InstrumentName__r.NCCode__c);
            d.put('mcode',tt.MCode__c );
            d.put('outdoor_way',tt.Outgoingway__c );
            d.put('enter_way', tt.EnterWay__c);
            d.put('task_resource',tt.TaskSource__c );

            d.put('outdoor_no', tt.OutgoingNumber__c);
            d.put('invtype', tt.InstrumentType__c);
            d.put('coop_year', tt.Numberofyears__c);
            d.put('contract_year',tt.ContractYear__c );
            d.put('contract_start_date',tt.ContractStartDate__c == null ? '': tt.ContractStartDate__c.format() );
            d.put('contract_end_date', tt.ContractEndDate__c == null ? '': tt.ContractEndDate__c.format());
            d.put('contract_no', tt.ContractNumber__c);
            d.put('pack_way',tt.OverallPackagingMode__c);
            d.put('is_have_contract',tt.Contract__c);
            d.put('is_have_mc', tt.CalculationTable__c);
            d.put('coop_type', tt.MKCooperationType__c);
            d.put('outdoor_date',tt.OutdoorDate__c == null ? '': tt.OutdoorDate__c.format() );

            d.put('sf_mc_no', tt.EstimateNumber__c);
            d.put('sub_cost', String.valueOf(tt.SubcompanyInstrumentDeliveryCost__c));
            d.put('group_cost', String.valueOf(tt.InstrumentDeliveryCost__c));

           //d.put('is_trid_from_contract', tt.IsTridFromContract__c );
            d.put('detail_note', tt.TaskDetailNote__c);
            d.put('equip_note', tt.EquipNote__c);
            d.put('tax', String.valueOf(tt.Tax__c));
            for (TaskTrackingDetailImport__c ttdi  : tt.TaskTrackingImport__r ) {
                d.put('regent_cate1', ttdi.Classification1__c);
                d.put('regent_cate2', ttdi.Classification2__c);
                d.put('regent_brand', ttdi.ReagentBrand__c);
                d.put('is_need_add_task', ttdi.WhetherNew__c);
                d.put('is_need_replace_task', ttdi.WhetherCovered__c);
                d.put('assign_'+ttdi.Years__c, String.valueOf(ttdi.ReagentAssignments__c));

                //d.put('sub_profit_'+ttdi.Years__c, String.valueOf(ttdi.SubCompanyGrossProfit__c));
                //d.put('group_profit_'+ttdi.Years__c,String.valueOf(ttdi.GroupGrossProfit__c));

            }

            datas.add(d);
        }
        System.debug(accSet);
                System.debug(iemiset);

        Map<String, TaskEquipment__c> teMap = new Map<String,TaskEquipment__c>();
        for (TaskEquipment__c te  :[select Id,Name ,Standers__r.Account__r.Name ,Standers__r.Company__c  , SerialNo__c from TaskEquipment__c  where Standers__r.Company__c   in:accset and SerialNo__c in:iemiset ] ) {

        	teMap.put(te.Standers__r.Company__c +'-'+te.SerialNo__c,te);


        }
        System.debug(teMap);
        accset.clear();
        iemiset.clear();

        for (Map<String,String> d  :datas  ) {
       		
       		String key = shortcomMap.get(d.get('owner_area' ))+'-'+d.get('iemi' );
       		if(teMap.containsKey(key)){
       			TaskEquipment__c te = teMap.get(key); 
       			d.put('tequip_id', te.Id );
       			d.put('tequip_name', te.Name );
       		}
	
        }

        dataJson = EncodingUtil.urlEncode(JSON.serialize(datas), 'UTF-8');

    }


    //将数据转换为Id 
    @RemoteAction 
    public static String validateRefValue(Map<String ,List<String>> objectFieldMap , Map<String,List<String>> vMap ){

    		


    		System.debug(vMap);
    		Set<String> notMatch = new  Set<String> ();
    		if(vMap.isEmpty()) return EncodingUtil.urlEncode(JSON.serialize(notMatch) ,'UTF-8');
	    	for(String sObjectName : objectFieldMap.keySet()){

	    		if(!vMap.containsKey(sObjectName))continue;

	    		String sql = 'select  ';
	    		String fieldsql =  String.join(objectFieldMap.get(sObjectName), ',') ;

	    		if(!fieldsql.contains('Id')) fieldsql += ',Id ';

	    		sql = sql + fieldsql + ' from ' + sObjectName +' where ' ;

	    		List<String> cs = new List<String>();
	    		System.debug(sObjectName +' '+ objectFieldMap.get(sObjectName));
             	for(String field : objectFieldMap.get(sObjectName)){

             		String c = field+  ' in (\''+ String.join( vMap.get(sObjectName), '\',\'' )+'\')  '; 
             		cs.add(c);
             	}
             	sql += String.join(cs, ' or ');


             	System.debug(sql);

             	List<SObject> data = Database.query(sql);

             	Set<String> values =new  Set<String>();
             	for(SObject s : data){

             		for ( String field : objectFieldMap.get(sObjectName) ) {
             			values.add((String)s.get(field) );
             		}

             	}

             	//Set<String> notMatchVal=  new Set<String>();

             	for (String  val : vMap.get(sObjectName) ) {
             		
             		if(!values.contains(val)){

             			notMatch.add(val);
             		}	
             	}
             	//if(!notMatchVal.isEmpty())notMatch.put(sObjectName,notMatchVal);
	    		
	    	}

	    return EncodingUtil.urlEncode(JSON.serialize(notMatch) ,'UTF-8');
	    	

    }

     
    public  void deleteImport( ){
    	msg = '';
    	isSuc = false;
        List<Object> ids  = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8')) ;
        List<String> ids1 = new  List<String>();
        for (Object o  : ids ) {
            ids1.add(String.valueOf(o));
        }
        SavePoint sp = Database.setSavepoint();
        if(ids.isEmpty())msg =  '没有数据!';
        if(msg.length() > 0 )return;
        try {
            delete  [select Id from TaskTrackingDetailImport__c where TaskTrackingImport__c in: ids1  and TaskTrackingImport__r.IsSplited__c != true ];
            delete  [select Id from TaskTrackingImport__c where Id in: ids1 and  IsSplited__c != true ];
            msg =  '操作成功!';
            isSuc = true;
        }
        catch (Exception e) {
            Database.rollback(sp);
            msg =  '操作失败:'+e.getMessage();
        }
        
    }

    public Map<String ,String> getCompanyMap(Boolean isReverse ){
    	 Map<String ,String> comMap = new Map<String,String>();
        for(String com : Label.ShortCompanyName.split(',',-1)){
            List<String> cs = com.split('-',-1);
            if(cs != null && cs.size() > 1){
            	if(isReverse){
            		comMap.put(cs[0],cs[1]);
            	}else{
            		comMap.put(cs[1],cs[0]);
            		 comMap.put('东区','MKSW');
				     comMap.put('南区','MKSW' );
				     comMap.put('西区','MKSW' );
				     comMap.put('北区','MKSW' );
				     comMap.put('中区','MKSW' );
            	}
            }
        }
       
        return comMap;
    }
    
    public  void  save (){

    	isSuc = false;
    	msg = '';
        Map<String,Object> resultMap = new Map<String,Object>();
        List<Object> cList = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

        System.debug(cList);
        if(cList.isEmpty())msg = '没有数据!';
        if(msg.length() > 0 )return;
        Map<String,String> prodMap = new Map<String,String>();
        Map<String,TaskTrackingImport__c> ttiMap = new Map<String,TaskTrackingImport__c>();
        Map<String,String> mcodeMap = new Map<String,String>();
        Set<String> accSets = new Set<String>();

        // Set<String>mcSet = new Set<String>();
        // Set<String>contractSet = new Set<String>();
        Set<String>  exisets = new Set<String>();
         Set<String> mcode = new Set<String>();
        for(Object o :cList ){
            Map<String,Object> mo = (Map<String,Object>)o;
            mcodeMap.put(getStringValue(mo.get('mcode')), null);
            String nccode = getStringValue(mo.get('nccode'));
         
            accSets.add(getStringValue(mo.get('sf_ter_account_id')));
            accSets.add(getStringValue(mo.get('sf_pay_account_id')));

            if(nccode != null &&  nccode != '')prodMap.put(nccode,'');
            String detailId = getStringValue(mo.get('sfid'));
            if(String.isNotBlank(detailId))exisets.add(detailId);
            // String mcno = getStringValue(mo.get('sf_mc_no'));
            // if(String.isNotBlank(mcno))mcSet.add(mcno);

            // String contractno = getStringValue(mo.get('contract_no')); 
            // if(String.isNotBlank(contractno))contractSet.add(contractno);
             mcode.add((String)mo.get('mcode'));


        }

        Set<String> errors = new Set<String>();
        for ( TaskEquipment__c m : [select MCode__c from TaskEquipment__c where MCode__c in: mcode ] ) {
            errors.add(m.MCode__c);
        }
        for ( TaskAmount__c m : [select MCode__c from TaskAmount__c where MCode__c in: mcode ] ) {
            errors.add(m.MCode__c);
        }

        if(errors.size() > 0 ) throw new DmlException( '导入识别码重复: '+String.join(new List<String>(errors), ','));


        Map<String,String >accMap =new Map<String,String>();
        Map<String,String> accCoopTypeMap = new Map<String,String>();
        for ( Account acc  :[select Id ,Name ,AccountNumber,MKCooperationType__c from Account where Id in:accSets or Name in:accSets or AccountNumber in:accSets ] ) {
        	accMap.put(acc.Id,acc.Id);
        	accMap.put(acc.Name,acc.Id);
        	accMap.put(acc.AccountNumber,acc.Id);
        	accCoopTypeMap.put(acc.Id,acc.MKCooperationType__c);

        }
        accSets.clear();
        

         for ( Object o :cList) {
         	   Map<String,Object> mo = (Map<String,Object>)o;

        	  String onlykey = accMap.get(getStringValue(mo.get('sf_ter_account_id')))
                            + accMap.get(getStringValue(mo.get('sf_pay_account_id')))
                            +getStringValue(mo.get('owner_area'))
                            +getStringValue(mo.get('owner_year_month'))
                            +getStringValue(mo.get('sign_company'))
                            +getStringValue(mo.get('regent_brand'))
                            +getStringValue(mo.get('regent_cate1'))
                            +getStringValue(mo.get('regent_cate2'))
                            +getStringValue(mo.get('nccode'))
                            +getStringValue(mo.get('iemi'))
                            +getStringValue(mo.get('outdoor_no'));

                            

            ttiMap.put(onlykey,null );
        }

        for ( TaskTrackingImport__c tti : [select Id ,MCode__c,Only__c from TaskTrackingImport__c where (MCode__c in: mcodeMap.keySet()  or Only__c in:ttiMap.keySet()) and Id not in:exisets ]) {
            mcodeMap.put(tti.MCode__c, tti.Id );
            ttiMap.put(tti.Only__c,tti);
        }
        Map<String,Product__c> prodNameMap = new Map<String,Product__c>();

        for(Product__c p :[select Id ,NCCode__c,Name,ProductName__c,swjhdj__c,Brand__c  from Product__c where NCCode__c in: prodMap.keySet()]){
            
            prodMap.put(p.NCCode__c, p.Id);
          
            prodNameMap.put(p.Id, p  );
        }
     

       Map<String,String> comMap = getCompanyMap(false);
       
        List<TaskTrackingImport__c> impList = new List<TaskTrackingImport__c>();
        List<TaskTrackingDetailImport__c> d_implist  = new List<TaskTrackingDetailImport__c>();
        Set<String> onlykeys = new Set<String>();
       // Map<String,String> pTypeMap = ImportObject.getPicklistValues('Account','MKCooperationType__c',true);

        String rtId = Utils.getRecordTypeIdByDevNameAndObjName('ConfirmationForm', 'TaskTrackingImport__c');

    

        for(Object o : cList){
            Map<String,Object> mo = (Map<String,Object>)o;

            try{

                if( mo.get('mcode') == null )throw new DmlException('识别码必填!');
               
          
                if(mcodeMap.get(getStringValue(mo.get('mcode'))) != null )throw new DmlException(getStringValue(mo.get('mcode'))+'已存在该识别码的数据,检查是否重复导入');
             
                if(accMap.get(getStringValue(mo.get('sf_ter_account_id'))) == null || accMap.get(getStringValue(mo.get('sf_pay_account_id'))) == null )throw new DmlException(getStringValue(mo.get('mcode'))+'SF开票客户ID 或者 SF终端客户ID错误!');
             
               // Account acc1 =  [select Id ,MKCooperationType__c from Account where Id=: accMap.get(getStringValue(mo.get('sf_pay_account_id')))];
                
                //if(pTypeMap.get(  accCoopTypeMap.get(accMap.get(getStringValue(mo.get('sf_pay_account_id')))) )  != getStringValue(mo.get('coop_type')) ) throw new DmlException(getStringValue(mo.get('mcode'))+'项目合作类型与开票客户项目合作类型与不一致!');
            

                if(!comMap.containsKey(getStringValue(mo.get('sign_company'))))new DmlException(getStringValue(mo.get('mcode'))+'子公司(签约公司) 填写错误!');
             
                if(!comMap.containsKey(getStringValue(mo.get('owner_area'))))new DmlException(getStringValue(mo.get('mcode'))+'归属公司(大区/子公司) 填写错误!');
             


                 String onlykey = accMap.get(getStringValue(mo.get('sf_ter_account_id')))
                            +accMap.get(getStringValue(mo.get('sf_pay_account_id')))
                            +getStringValue(mo.get('owner_area'))
                            +getStringValue(mo.get('owner_year_month'))
                            +getStringValue(mo.get('sign_company'))
                            +getStringValue(mo.get('regent_brand'))
                            +getStringValue(mo.get('regent_cate1'))
                            +getStringValue(mo.get('regent_cate2'))
                            +getStringValue(mo.get('nccode'))
                            +getStringValue(mo.get('iemi'))
                            +getStringValue(mo.get('outdoor_no'));

                if(ttiMap.get(onlykey) != null ) throw new DmlException(getStringValue(mo.get('mcode'))+'数据可能存在重复,请核实!组合键为:'+onlykey + '重复的识别码:'+ ttiMap.get(onlykey).MCode__c );
              
                TaskTrackingImport__c tti = new TaskTrackingImport__c();
                tti.RecordTypeId = rtId;
                tti.Id = getStringValue(mo.get('sfid'));

                tti.Outgoingway__c = getStringValue(mo.get('outdoor_way'));
                tti.EnterWay__c = getStringValue(mo.get('enter_way'));
                
                tti.TaskSource__c = getStringValue(mo.get('task_resource'));

                if(String.isBlank(tti.TaskSource__c))new DmlException('任务量来源不能为空!');
              
                tti.OutgoingNumber__c = getStringValue(mo.get('outdoor_no'));

                tti.EquipNote__c = getStringValue(mo.get('equip_note'));
                tti.TaskDetailNote__c = getStringValue(mo.get('detail_note'));

               // tti.IsTridFromContract__c = getStringValue(mo.get('is_trid_from_contract'));
                tti.RegentBrand__c = getStringValue(mo.get('regent_brand'));

                String prodId =  prodMap.get(getStringValue(mo.get('nccode'))) ;
                if((prodId ==  null ||  prodId == '') && getStringValue(mo.get('nccode')) != null &&  getStringValue(mo.get('nccode')) != '' )throw  new DmlException(getStringValue(mo.get('mcode'))+'仪器未匹配到产品:'+getStringValue(mo.get('nccode')));
               

                tti.InstrumentName__c = prodId== null ||  prodId == '' ? null : prodId ;

                // if(tti.InstrumentName__c != null && (prodNameMap.get(getStringValue(mo.get('nccode'))).ProductName__c != getStringValue(mo.get('invname')) )  )new DmlException('仪器名称不一致 请核实数据是否有误:'+getStringValue(mo.get('invname')) +'==='+ prodNameMap.get(getStringValue(mo.get('nccode'))));
               

                tti.SerialNo__c = getStringValue(mo.get('iemi'));
                tti.Numberofyears__c = getStringValue(mo.get('coop_year'));

                tti.InstrumentType__c = getStringValue(mo.get('invtype'));//仪器规格型号
                tti.Mcode__c = getStringValue(mo.get('mcode'));//识别码
              

                tti.Enddateofinstrument__c = getDateValue(mo.get('coop_end_date'));
                if(tti.Enddateofinstrument__c == null)throw new DmlException(getStringValue(mo.get('mcode'))+'合作截止日期格式错误! 格式为:yyyy-MM-dd');
            

                tti.Instrumentstartdate__c = getDateValue(mo.get('coop_start_date'));
                if(tti.Enddateofinstrument__c == null)throw new DmlException(getStringValue(mo.get('mcode'))+'合作起算日期格式错误! 格式为:yyyy-MM-dd');
              

                // Decimal    coopYs = Decimal.valueOf(tti.Numberofyears__c);
              
                // if(tti.Instrumentstartdate__c.monthsBetween(tti.Enddateofinstrument__c) +1 != Integer.valueOf(coopYs * 12))new DmlException('合作起止日期与合作年限不匹配');
                // Integer endy = tti.Enddateofinstrument__c.year();
                // boolean isnerr  = false;
                // for(Integer i = endy+1 ; i < endy+10; i ++){

                //     if(mo.get('assign_'+i) != null   ){

                //         isnerr = true; 
                //         break;
                //     }
                // }
                // if(isnerr)throw new DmlException('任务量超出合作截止日期!');
              

                tti.ContractYear__c = getStringValue(mo.get('contract_year'));
                tti.MKCooperationType__c = getStringValue(mo.get('coop_type'));
                tti.ContractStartDate__c =  getDateValue(mo.get('contract_start_date'));
                tti.ContractEndDate__c =  getDateValue(mo.get('contract_end_date'));

                tti.Company__c = comMap.get(getStringValue(mo.get('sign_company')));
                tti.OwnerCompany__c = getStringValue(mo.get('owner_area'));
                tti.OwnerYM__c = getStringValue(mo.get('owner_year_month'));

                //自产仪器: 生物计划单价 (- 不含税售价(非正常销售))
                tti.EquipTaxPrice__c = getDecimalValue(mo.get( 'tax_price'));

                tti.SubcompanyInstrumentDeliveryCost__c =  getDecimalValue(mo.get('sub_cost'));
                //自产
                System.debug(prodNameMap);
                System.debug(tti.InstrumentName__c);

                if(!String.isBlank(tti.InstrumentName__c)){
                	if(MaccuraBrandUtil.maccura.contains(prodNameMap.get(tti.InstrumentName__c).Brand__c)){

	                	if(prodNameMap.get(tti.InstrumentName__c).swjhdj__c == null ) throw new DmlException(getStringValue(mo.get('mcode'))+'仪器没有生物计划单价:'+ prodNameMap.get(tti.InstrumentName__c).NCCode__c);

	                	tti.InstrumentDeliveryCost__c = tti.EnterWay__c == '非正常销售投放' ? (prodNameMap.get(tti.InstrumentName__c).swjhdj__c/10000 -  (tti.EquipTaxPrice__c == null ? 0 :  tti.EquipTaxPrice__c ) / 1.13 ) : prodNameMap.get(tti.InstrumentName__c).swjhdj__c/10000;

	                	if(tti.InstrumentDeliveryCost__c != null && tti.InstrumentDeliveryCost__c < 0 )tti.InstrumentDeliveryCost__c = 0;
	                }else{// 代理

	                	tti.InstrumentDeliveryCost__c = tti.SubcompanyInstrumentDeliveryCost__c;

	                }
                }
                

                //tti.SubRito__c = getDecimalValue(mo.get('sub_rito'));
                 //getDecimalValue(mo.get('group_cost'));
                
                tti.OverallPackagingMode__c = getStringValue(mo.get('pack_way'));
                tti.Contract__c = getStringValue(mo.get('is_have_contract'));
                tti.CalculationTable__c = getStringValue(mo.get('is_have_mc'));

                tti.ContractNumber__c = getStringValue(mo.get('contract_no'));

                
                tti.OutdoorDate__c = getDateValue(mo.get('outdoor_date')); 

                tti.Account__c =  accMap.get(getStringValue(mo.get('sf_pay_account_id')));
                Map<String,String> cM = ImportObject.getPicklistValues('Contract__c','Corpcode__c',true);



                tti.TerminalCustomer__c = accMap.get(getStringValue(mo.get('sf_ter_account_id'))) ;
                tti.EstimateNumber__c = getStringValue(mo.get('sf_mc_no'));
                tti.Only__c = onlykey; //getStringValue(mo.get('owner_year_month'));

                String cate1 = getStringValue(mo.get('regent_cate1')); 
                String cate2 = getStringValue(mo.get('regent_cate2')); 
                String brand = getStringValue(mo.get('regent_brand')); 
               // String isadd = getStringValue(mo.get('is_need_add_task'));
               // String iscover  = getStringValue(mo.get('is_need_replace_task'));


               // if(cate1 == null || cate2 == null || brand == null)throw new DmlException('追踪试剂 一级分类 二级分类 品牌 必填!');
               

                Integer y = System.now().year() + 16;
                

                for(Integer i = 2010 ; i < y ; i ++){
                    TaskTrackingDetailImport__c ttdi = new TaskTrackingDetailImport__c();
                    String year = String.valueOf(i);
                    if(mo.get('assign_'+year) == null   )continue;
                    ttdi.MCode__c = getStringValue(mo.get('mcode'));
                    ttdi.Years__c = year;
                    //ttdi.WhetherNew__c= isadd;
                   // ttdi.WhetherCovered__c = iscover;
                    ttdi.Classification1__c = cate1;
                    ttdi.Classification2__c = cate2;
                    ttdi.ReagentBrand__c = brand ;
                    ttdi.ReagentAssignments__c  = getDecimalValue(mo.get('assign_'+year));
                    //子公司毛利
                   // ttdi.SubCompanyGrossProfit__c = multi(tti.SubRito__c , ttdi.ReagentAssignments__c );
                    //集团毛利
                  //  ttdi.GroupGrossProfit__c = MaccuraBrandUtil.maccura.contains(brand) ?  multi((0.7 +  multi(tti.SubRito__c , 0.3 ))  , ttdi.ReagentAssignments__c ) : ttdi.SubCompanyGrossProfit__c ;

                    if(ttdi.ReagentAssignments__c == null) continue;
                   // ttdi.GroupGrossProfit__c = getDecimalValue(mo.get('group_profit_'+year)); 
                    d_implist.add(ttdi);
                }
                impList.add(tti);


             

            }catch(Exception e){
               
                 msg = '保存失败:'+ e.getMessage();
                 return;

            }
            
        }

        SavePoint sp = Database.setSavepoint();
       try{
               
               System.debug(approvalT);
               if(approvalT.Id == null )insert approvalT;

               for(TaskTrackingImport__c tti : impList){
                    tti.MainApply__c = approvalT.Id;
                  
               }

               upsert impList ; 

               Map<String,String> tMap = new Map<String,String>();
               System.debug(impList);
               for(TaskTrackingImport__c tti : impList){
                    tMap.put(tti.Mcode__c,tti.Id);
                    tti.MainApply__c = approvalT.Id;

               }
               for(TaskTrackingDetailImport__c ttdi : d_implist){
                    ttdi.TaskTrackingImport__c = tMap.get(ttdi.Mcode__c);
               }
               System.debug(d_implist);
                List<TaskTrackingDetailImport__c > deleList = [select Id from TaskTrackingDetailImport__c where  TaskTrackingImport__c in: tMap.values()];
                if(deleList.size() > 0) delete deleList;
               if(d_implist.size()> 0) insert  d_implist ;

               backId = approvalT.Id;
               msg = '保存成功!';
               isSuc = true;


       }catch(Exception e ){


            Database.rollback(sp);
            approvalT.Id = backId;


           msg = '保存失败:'+ e.getMessage()+e.getStackTraceString();
        
       } 

     
       

    }
    public static Decimal multi(Decimal a ,Decimal b){
    	if(a == null || b == null)return null;
    	return a * b ;
    }
    public static Boolean getBooleanValue(Object o){
        if(o == null) return null;
        if(getStringValue(o) == '是')return true;
        if(getStringValue(o) == '否')return false;
        return null;
    }
    public static Date getDateValue(Object o ){
        if(o == null) return null;
        try{
            return Date.valueOf(String.valueOf(o).trim());
        }catch(Exception e){
            return null;
        }
    }
    public static Decimal getDecimalValue(Object o){
        if(o == null)return null;
        String d = String.valueOf(o).trim();
        if(d == '')return null;
        return Decimal.valueOf(d);
    }
   /* public static String  getTTAccountID(String accid){
        if(accid == null )return null ;
        try{
            return String.valueOf(Id.valueOf(accid));
        }catch(Exception e){
            return null;
        }
    }*/
    public static String getStringValue(Object o){
        if(o == null)return null;
        return String.valueOf(o).trim();
    }

    /*
    * 获取没有拆分的 手工导入的任务量信息
    
    @RemoteAction
    public static String getTaskImport(){
        List<Map<String,String>> datas = new List<Map<String,String>>();
        //
        Map<String,String>  comMap  = ImportObject.getPicklistValues('TaskTrackingImport__c','Company__c', true );
        for(TaskTrackingImport__c tt :[select Id ,Instrumentstartdate__c  , Enddateofinstrument__c,TaskSource__c,
            OwnerCompany__c,OwnerYM__c,Company__c,MCode__c,Outgoingway__c,EnterWay__c,
            OutgoingNumber__c,InstrumentType__c,SerialNo__c,Numberofyears__c,ContractYear__c,
            ContractStartDate__c,ContractEndDate__c,ContractNumber__c,OverallPackagingMode__c,Contract__c,
            CalculationTable__c,MKCooperationType__c,OutdoorDate__c,EstimateNumber__c,
            SubRito__c,EquipTaxPrice__c,
            Account__r.Name , TerminalCustomer__r.Name ,InstrumentDeliveryCost__c,SubcompanyInstrumentDeliveryCost__c,
            InstrumentName__r.ProductName__c  ,IsSplited__c ,InstrumentName__r.NCCode__c,Tax__c,EquipNote__c,TaskDetailNote__c,
            (select Classification1__c, Classification2__c,ReagentBrand__c,GroupGrossProfit__c,SubCompanyGrossProfit__c,
             Years__c,WhetherNew__c,WhetherCovered__c,ReagentAssignments__c
             from TaskTrackingImport__r )
            from TaskTrackingImport__c where IsSplited__c =false  order by Mcode__c ]){
            Map<String,String> d = new Map<String,String>();
            d.put('sfid', tt.Id);
            d.put('owner_year_month',tt.OwnerYM__c  );
            d.put('owner_area', tt.OwnerCompany__c);
            d.put('sign_company',comMap.get(tt.Company__c ));
            d.put('sf_pay_account_id', tt.Account__r.Name );
            d.put('sf_ter_account_id',tt.TerminalCustomer__r.Name  );
            d.put('invname', tt.InstrumentName__r.ProductName__c);
            d.put('iemi', tt.SerialNo__c );         
            d.put('coop_start_date', tt.Instrumentstartdate__c.format());
            d.put('coop_end_date',tt.Enddateofinstrument__c.format() );

            d.put('sub_rito',String.valueOf(tt.SubRito__c) );
            d.put('tax_price',String.valueOf(tt.EquipTaxPrice__c) );

            d.put('nccode', tt.InstrumentName__r.NCCode__c);
            d.put('mcode',tt.MCode__c );
            d.put('outdoor_way',tt.Outgoingway__c );
            d.put('enter_way', tt.EnterWay__c);
            d.put('task_resource',tt.TaskSource__c );

            d.put('outdoor_no', tt.OutgoingNumber__c);
            d.put('invtype', tt.InstrumentType__c);
            d.put('coop_year', tt.Numberofyears__c);
            d.put('contract_year',tt.ContractYear__c );
            d.put('contract_start_date',tt.ContractStartDate__c == null ? '': tt.ContractStartDate__c.format() );
            d.put('contract_end_date', tt.ContractEndDate__c == null ? '': tt.ContractEndDate__c.format());
            d.put('contract_no', tt.ContractNumber__c);
            d.put('pack_way',tt.OverallPackagingMode__c);
            d.put('is_have_contract',tt.Contract__c);
            d.put('is_have_mc', tt.CalculationTable__c);
            d.put('coop_type', tt.MKCooperationType__c);
            d.put('outdoor_date',tt.OutdoorDate__c == null ? '': tt.OutdoorDate__c.format() );

            d.put('sf_mc_no', tt.EstimateNumber__c);
            d.put('sub_cost', String.valueOf(tt.SubcompanyInstrumentDeliveryCost__c));
            d.put('group_cost', String.valueOf(tt.InstrumentDeliveryCost__c));

           //d.put('is_trid_from_contract', tt.IsTridFromContract__c );
            d.put('detail_note', tt.TaskDetailNote__c);
            d.put('equip_note', tt.EquipNote__c);
            d.put('tax', String.valueOf(tt.Tax__c));
            for (TaskTrackingDetailImport__c ttdi  : tt.TaskTrackingImport__r ) {
                d.put('regent_cate1', ttdi.Classification1__c);
                d.put('regent_cate2', ttdi.Classification2__c);
                d.put('regent_brand', ttdi.ReagentBrand__c);
                d.put('is_need_add_task', ttdi.WhetherNew__c);
                d.put('is_need_replace_task', ttdi.WhetherCovered__c);
                d.put('assign_'+ttdi.Years__c, String.valueOf(ttdi.ReagentAssignments__c));
                d.put('sub_profit_'+ttdi.Years__c, String.valueOf(ttdi.SubCompanyGrossProfit__c));
                d.put('group_profit_'+ttdi.Years__c,String.valueOf(ttdi.GroupGrossProfit__c));

            }



            datas.add(d);
        }

        return EncodingUtil.urlEncode(JSON.serialize(datas), 'UTF-8') ;
    }
*/

    /*
    *拆分手动导入的任务量
    */
    @RemoteAction
    public static String splitTaskFromImp(String taskId){
        Map<String,Object> resultMap = new Map<String,Object>();
        //1.查询导入的任务量主表
        TaskTrackingImport__c tti  = null ; 
        try{
            tti = [select Id ,Instrumentstartdate__c  , Enddateofinstrument__c,OwnerCompany__c,TaskSource__c,
                InstrumentName__r.ProductName__c,EnterWay__c,Numberofyears__c,EstimateNumber__c,
                ContractNumber__c,MCode__c,InstrumentType__c,Company__c,
            Account__c, TerminalCustomer__c,InstrumentDeliveryCost__c,SubcompanyInstrumentDeliveryCost__c,
            InstrumentName__c,SerialNo__c ,IsSplited__c ,CalculationTable__c ,OutdoorDate__c,OutgoingNumber__c,
            ContractStartDate__c,ContractEndDate__c,Outgoingway__c,EquipNote__c,TaskDetailNote__c,Tax__c


            ,(select Id , Years__c, ReagentAssignments__c , Classification1__c , GroupGrossProfit__c, 
                Classification2__c, ReagentBrand__c,SubCompanyGrossProfit__c , WhetherCovered__c 
                from tt.TaskTrackingImport__r where TaskTrackingImport__c =:taskId )

             from TaskTrackingImport__c tt  where Id=:taskId];

        }catch(Exception e){}
        if(tti == null )return EncodingUtil.urlEncode(JSON.serialize(setResult(false,'任务量ID错误!')), 'UTF-8') ;

        if(tti.IsSplited__c)return EncodingUtil.urlEncode(JSON.serialize(setResult(false,'该任务量已拆分,请不要重复拆分!')), 'UTF-8') ;

        //2.查询导入的任务量明细
        List<TaskTrackingDetailImport__c> ttList = tti.TaskTrackingImport__r;

        ///匹配公司
         Map<String ,String> comMap = new Map<String,String>();
        for(String com : Label.ShortCompanyName.split(',',-1)){
            List<String> cs = com.split('-',-1);
            if(cs != null && cs.size() > 1)comMap.put(cs[1],cs[0]);
        }
        comMap.put('东区','MKSW' );
        comMap.put('南区','MKSW' );
        comMap.put('西区','MKSW' );
        comMap.put('北区','MKSW' );
        comMap.put('中区','MKSW' );

        if(comMap.get(tti.OwnerCompany__c) == null )return EncodingUtil.urlEncode(JSON.serialize(setResult(false,'所属公司未匹配到,请检查数据 : '+ tti.OwnerCompany__c +' 或 联系管理员维护子公司 Label.ShortCompanyName' )), 'UTF-8') ;
        //3.找到任务量追踪总表; 无则 新建任务量追踪总表
        CooperationStandard__c cs  = null ;
        try{
             cs =  [select Id ,Company__c ,EndingDate__c,StartingDate__c  from CooperationStandard__c  where NewData__c = true 
            and Account__c =:tti.Account__c and TerminalCustomer__c =:tti.TerminalCustomer__c limit  1 ]; 
            if(cs.EndingDate__c.daysBetween(tti.Enddateofinstrument__c) > 0)cs.EndingDate__c = tti.Enddateofinstrument__c;
            if(comMap.get(tti.OwnerCompany__c) == null) return   EncodingUtil.urlEncode(JSON.serialize(setResult(false,'导入的所属公司异常!')), 'UTF-8') ;
            if(cs.Company__c != null && cs.Company__c  != comMap.get(tti.OwnerCompany__c)) return EncodingUtil.urlEncode(JSON.serialize(setResult(false,'导入的所属公司不一致!总表ID:'+cs.Id +'导入:'+tti.OwnerCompany__c +' 总表: '+cs.Company__c)), 'UTF-8') ;
            if(cs.Company__c == null)cs.Company__c =  comMap.get(tti.OwnerCompany__c) ;
            if(tti.Instrumentstartdate__c  != null && tti.Instrumentstartdate__c.daysBetween(cs.StartingDate__c) > 0 )cs.StartingDate__c = tti.Instrumentstartdate__c;
        }catch(Exception e){
            cs =  new CooperationStandard__c();
            cs.Account__c = tti.Account__c;//开票客户
            cs.TerminalCustomer__c = tti.TerminalCustomer__c;
            cs.NewData__c = true; //标记是新生成的任务量主表
            //cs.CSQuote__c = tti.CalculationTable__c;
            cs.Company__c = comMap.get(tti.OwnerCompany__c)  ;
            cs.StartingDate__c = tti.Instrumentstartdate__c;
            cs.EndingDate__c = tti.Enddateofinstrument__c;
           // cs.company__c = comMap.get(tti.OwnerCompany__c);

        }

        //4.拆分仪器 到追踪总表 下的仪器表
        TaskEquipment__c  te = null ;
        if( tti.InstrumentName__c  != null ){
            //4.1判断 投放仪器中是否存在此台仪器 ; 若存在,则报错
            if(cs.Id != null ){
               List<TaskEquipment__c>  teL = [select Id from TaskEquipment__c where Standers__c =:cs.Id  and 
               InstrumentName__c =:tti.InstrumentName__c and Mcode__c =: tti.MCode__c  and NewData__c = true  ];
              
               if(teL != null && teL.size() > 0) return EncodingUtil.urlEncode(JSON.serialize(setResult(false,'仪器已存在任务量总表!总表ID:'+cs.Id + ' 仪器ID '+tti.InstrumentName__c + ' 识别码: '+ tti.Mcode__c )), 'UTF-8') ;

            }
            te = new TaskEquipment__c();
            te.NewData__c = true ;//标记为新的数据
            te.InstrumentName__c = tti.InstrumentName__c ;
            te.SerialNo__c = tti.SerialNo__c;//机身号
            te.SubcompanyInstrumentDeliveryCost__c = tti.SubcompanyInstrumentDeliveryCost__c;//子公司成本
            te.InstrumentDeliveryCost__c = tti.InstrumentDeliveryCost__c ;//集团成本
            te.OutdoorDate__c = tti.OutdoorDate__c ;//出库日期
            te.Contractnumber__c = tti.ContractNumber__c;//合同编号
            te.EnterWay__c = tti.EnterWay__c ; //进入方式
            te.OutgoingNumber__c = tti.OutgoingNumber__c;//出库单号
            te.Numberofyears__c = tti.Numberofyears__c; //合作年限
            te.Instrumentstartdate__c = tti.Instrumentstartdate__c ; //合作起算日期
            te.Enddateofinstrument__c = tti.Enddateofinstrument__c ;//合作截止日期

            te.TaskSource__c = tti.TaskSource__c;

            te.ProductName__c  = tti.InstrumentName__r.ProductName__c ;
            te.Model__c = tti.InstrumentType__c;//仪器规格/型号
            te.Outgoingway__c = tti.Outgoingway__c ;//仪器出库方式;

            te.ContractStartDate__c = tti.ContractStartDate__c;//合同开始
            te.ContractEndDate__c = tti.ContractEndDate__c;//合同结束
            te.MCode__c = tti.MCode__c;//导入识别码

            te.Pingpai__c  = ttList[0].ReagentBrand__c ; 
            te.FirstClass__c = ttList[0].Classification1__c ; 
            te.Twolevel__c = ttList[0].Classification2__c ; 
            //te.WhetherFromContract__c = tti.IsTridFromContract__c;
            te.Note__c = tti.EquipNote__c ; 


        }

        ///查找测算
        String mc_no = null;
        if(tti.EstimateNumber__c != null ){

            try {
               mc_no =  [select Id  from Measure_Calculate__c where name =: tti.EstimateNumber__c.trim() ].Id  ;
            }
            catch (Exception e) {
                //resultMap.put('code', '0');
                //resultMap.put('msg','测算编号不存在!'+tti.EstimateNumber__c  );
                return EncodingUtil.urlEncode(JSON.serialize(setResult(false,'测算编号不存在!'+tti.EstimateNumber__c)), 'UTF-8') ; 
            }
            
        } 

        //5.拆分任务量 到追踪总表 下的任务量明细表 
        List<TaskAmount__c> tl  = new List<TaskAmount__c>();
        if(ttList.size() > 0){

            String stY =  String.valueOf(tti.Instrumentstartdate__c.year()) + '年';
            Set<String> stMs  = new Set<String>();
           for(Integer i = tti.Instrumentstartdate__c.month() ; i <=12 ; i ++){
                stMs.add(String.valueOf(i));
            }
            String enY =  String.valueOf(tti.Enddateofinstrument__c.year()) + '年';
            Set<String> enMs  = new Set<String>();
           for(Integer i =1 ; i <=tti.Enddateofinstrument__c.month()  ; i ++){
                enMs.add(String.valueOf(i));
            }
            Map<String ,TaskAmount__c > etMap = new Map<String,TaskAmount__c>();
      


            Map<String ,TaskAmount__c > tMap = new Map<String,TaskAmount__c>();


            for(TaskTrackingDetailImport__c t :ttList){

                if(t.Years__c == String.valueOf(tti.Instrumentstartdate__c.year())){
                    for(String m  : stMs){
                       TaskAmount__c ta =  genTaskAmountFromTTImport(t,m,stMs.size(),tti ,mc_no);
                       String key =  ta.Category1__c +'_'+ta.Brand__c +'_'+ta.Category2__c + '_'+ta.Year__c + '_'+ ta.Month__c;
                        tMap.put(key,ta);
                    }
                }else if(t.Years__c == String.valueOf(tti.Enddateofinstrument__c.year())){
                    for(String m : enMs){
                        TaskAmount__c ta =  genTaskAmountFromTTImport(t,m,enMs.size(),tti,mc_no);
                        String key =  ta.Category1__c +'_'+ta.Brand__c +'_'+ta.Category2__c + '_'+ta.Year__c + '_'+ ta.Month__c;
                        tMap.put(key,ta);
                    }
                }else{
                    for(Integer i = 1 ; i <= 12 ; i ++){
                        TaskAmount__c ta =  genTaskAmountFromTTImport(t,String.valueOf(i),12,tti,mc_no);
                        String key =  ta.Category1__c +'_'+ta.Brand__c +'_'+ta.Category2__c + '_'+ta.Year__c + '_'+ ta.Month__c;
                        tMap.put(key,ta);
                    }
                }
            }

            for(String k :tMap.keySet() ){

                //TaskAmount__c oldta = etMap.get(k);
                TaskAmount__c ta = tMap.get(k);

             

                tl.add(ta);

            }

        }
        SavePoint sp = Database.setSavepoint();
        try {
            //保存 总表
            System.debug('导入:=>'+cs);
            upsert cs; 
            //保存 投放仪器
           if(te !=  null ){
                te.Standers__c = cs.Id;
                upsert te;
           } 
           ///保存 任务量
            for(TaskAmount__c t : tl){
                t.Standers__c = cs.Id; 
            }
            System.debug(tl);
            if(tl.size() > 0)upsert tl;

            ///更新 标记
            tti.IsSplited__c = true ; 
            update tti;

            return EncodingUtil.urlEncode(JSON.serialize(setResult(true,'保存成功!')), 'UTF-8') ;
        }catch (Exception e) {
            
            Database.rollback(sp);
            return EncodingUtil.urlEncode(JSON.serialize(setResult(false,'保存失败'+e.getMessage() + '  '+e.getStackTraceString())), 'UTF-8') ;
        }

    }
     private static Map<String,Object> setResult(Boolean issuc ,String msg  ){
       Map<String,Object> resultMap = new Map<String,Object>();

       resultMap.put('code', issuc ? '1': '0');
        resultMap.put('msg', msg);
        return resultMap;

    }

     private static TaskAmount__c genTaskAmountFromTTImport(TaskTrackingDetailImport__c t,String m  , Integer siz ,TaskTrackingImport__c tti ,String mc_no ){

        TaskAmount__c ta = new TaskAmount__c();
        ta.MCode__c = tti.MCode__c;//
        ta.Category1__c = t.Classification1__c;
        ta.Category2__c = t.Classification2__c;
        ta.Brand__c = t.ReagentBrand__c;
        ta.Month__c = m ;
        ta.Year__c = t.Years__c+'年';
        ta.MeasureCalc__c = mc_no ;
        ta.CalculationTable__c = tti.CalculationTable__c;

        ta.Contractnumber__c = tti.ContractNumber__c;
        ta.AssignAmount__c = t.ReagentAssignments__c == null ? null : t.ReagentAssignments__c / siz ;
        ta.SubProfit__c = t.SubCompanyGrossProfit__c == null ?  null : t.SubCompanyGrossProfit__c / siz ;
        ta.GroupProfit__c = t.GroupGrossProfit__c == null ? null : t.GroupGrossProfit__c / siz ;  
       // ta.Cost__c = t.ReagentAssignments__c == null || t.SubCompanyGrossProfit__c == null ? null :(t.ReagentAssignments__c - t.SubCompanyGrossProfit__c ) / siz;
        ta.TaskTrackingDetailImport__c = t.Id;
        ta.TaskSource__c = tti.TaskSource__c;
        ta.Note__c = tti.TaskDetailNote__c;
        ta.Tax__c = tti.Tax__c;
        //ta.WhetherFromContract__c = tti.IsTridFromContract__c;
       //ta.AllMaccuraBrand__c = tti.AllMaccuraBrand__c;
        //ta.AllBrand__c = tti.AllBrand__c;
        ta.Origin__c = '手工导入';

        return ta;
    }
}